<template>
  <div class="lb-store-manage-edit">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <el-form
          @submit.native.prevent
          :model="subForm"
          ref="subForm"
          :rules="subFormRules"
          label-width="130px"
      >
        <el-form-item label="球厅名称" prop="ballroom_name">
          <el-input
              v-model="subForm.ballroom_name"
              maxlength="15"
              show-word-limit
              placeholder="请输入球厅名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="球厅门头照" prop="doorstep_photo">
          <lb-cover
              :fileList="subForm.doorstep_photo"
              @selectedFiles="getCover($event, 'doorstep_photo')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 160 * 160</lb-tool-tips>
        </el-form-item>
        <el-form-item label="球厅地址" prop="address_id">
          <el-input
              v-if="subForm.address_id"
              disabled
              type="text"
              :rows="10"
              v-model="addressInfo.address + addressInfo.address_info"
              maxlength="300"
              show-word-limit
              placeholder="球厅地址"
          ></el-input>
          <lb-button
              type="primary"
              class="getLocation"
              plain
              style="margin-left: 10px"
              @click="addressOpen"
          >
            选择地址
          </lb-button>
        </el-form-item>
        <el-form-item label="真实姓名" prop="user_name">
          <el-input
              v-model="subForm.user_name"
              maxlength="20"
              show-word-limit
              placeholder="请输入真实姓名"
          ></el-input>
          <lb-tool-tips>营业执照上的企业名称</lb-tool-tips>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input
              v-model="subForm.mobile"
              placeholder="请输入联系电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="关联用户" prop="user_id">
          <el-tag class="cursor-pointer" :type="have_user_id ? 'info' : 'primary'"
                  @click="toShowDialog">{{ subForm.user_id ? subForm.nickName : '选择关联用户' }}</el-tag>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitForm" v-preventReClick>{{
              $t('action.submit')
            }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
              $t('action.back')
            }}</lb-button>
        </el-form-item>
      </el-form>

      <lb-map
          :dialogVisible.sync="showMap"
          @selectedLatLng="getLatLng"
      ></lb-map>

      <el-dialog title="关联用户" :visible.sync="showDialog" width="800px" center>
        <el-form :inline="true" :model="searchForm" ref="serverSearchForm" label-width="70px">
          <el-form-item label="输入查询" prop="name">
            <el-input v-model="serverSearchForm.name" placeholder="请输入用户名称"></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button size="medium" type="primary" icon="el-icon-search" style="margin-right: 5px"
                       @click="getServerTableDataList(1)">{{ $t('action.search') }}</lb-button>
            <lb-button size="medium" icon="el-icon-refresh-left" style="margin-right: 5px"
                       @click="resetForm('serverSearchForm')">{{ $t('action.reset') }}</lb-button>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" ref="multipleTable" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
                  tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
        </el-table>
        <lb-page :slot="false" :batch="false" :page="searchForm.page" :pageSize="searchForm.limit" :total="total"
                 @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
        </span>
      </el-dialog>

      <address-list ref="addressListRef" @confirm="addressConfirm"></address-list>

    </div>
  </div>
</template>

<script>
import moment from 'moment'
import AddressList from '@/components/address/list'
export default {
  components: {
    AddressList
  },
  data () {
    let checkStar = (rule, value, callback) => {
      let reg = /^(([0-5]*)|(([0]\.\d{1}|[1-5]*\.\d{1})))$/
      if (value === '' || !reg.test(value) || value * 1 > 5) {
        callback(new Error(value === '' ? `请输入评分` : `请输入正确的评分，取值0至5，最多保留1位小数`))
      } else {
        callback()
      }
    }

    let checkAddress = (rule, value, callback) => {
      let isLng = /^[\-\+]?(0(\.\d{1,15})?|([1-9](\d)?)(\.\d{1,15})?|1[0-7]\d{1}(\.\d{1,15})?|180\.0{1,15})$/
      let isLat = /^[\-\+]?((0|([1-8]\d?))(\.\d{1,15})?|90(\.0{1,15})?)$/
      let { address, lat, lng } = this.subForm
      address = address ? address.replace(/(^\s*)|(\s*$)/g, '') : ''
      if (!address) {
        callback(new Error(`请输入球厅地址`))
      } else if (!lng || !isLng.test(lng)) {
        let msg = !lng ? `请输入球厅经度` : `请输入正确的经度`
        callback(new Error(msg))
      } else if (!lat || !isLat.test(lat)) {
        let msg = !lat ? `请输入球厅纬度` : `请输入正确的纬度`
        callback(new Error(msg))
      } else {
        callback()
      }
    }
    return {
      addressInfo: {},
      addressShowDialog: false,
      have_user_id: false,
      total: 0,
      serverSearchForm: {
        page: 1,
        limit: 10,
        name: ''
      },
      searchForm: {
        page: 1,
        limit: 10,
        nickName: ''
      },
      tableData: [],
      navTitle: '',
      showMap: false,
      showDialog: false,
      base_agent: [],
      subForm: {
        id: 0,
        address_id: 0,
        ballroom_name: '',
        doorstep_photo: [],
        user_name: '',
        mobile: '',
        user_id: '',
      },
      currentRow: {},
      subFormRules: {
        ballroom_name: { required: true, validator: this.$reg.isNotNull, text: '球厅名称', reg_type: 2, trigger: 'blur' },
        doorstep_photo: { required: true, type: 'array', message: '请上传球厅门头照', trigger: ['blur', 'change'] },
        address_id: { required: true, type: 'number', text: '请选择球厅地址', reg_type: 2, trigger: ['blur', 'change'] },
        user_name: { required: true, type: 'string', message: '请输入真实姓名', trigger: 'blur' },
        mobile: { required: true, validator: this.$reg.isAllPhone, text: '联系电话', trigger: 'blur' },
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    await this.getBaseInfo()
    if (id) {
      this.subForm.id = id
      this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.StoreEdit' : 'menu.StoreAdd')
  },
  methods: {
    addressConfirm (res) {
      this.addressInfo = res
      this.subForm.address_id = res.id
      console.log('this.subForm.address_id',this.subForm.address_id)
    },
    addressOpen () {
      this.$refs.addressListRef.showDialog = true;
    },
    async getTableDataList(flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let param = JSON.parse(JSON.stringify(this.searchForm))
      let {
        code,
        data
      } = await this.$api.technician.coachUserList(param)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    resetForm(form) {
      this.$refs[form].resetFields()
      this.getTableDataList(1)
    },
    async getServerTableDataList(flag) {
      if (flag) this.serverSearchForm.page = 1
      this.loading = true
      let param = JSON.parse(JSON.stringify(this.serverSearchForm))
      let {
        code,
        data
      } = await this.$api.service.serviceList(param)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    handleDialogConfirm() {
      if (this.currentRow === null || !this.currentRow.id) {
        this.$message.error(`请选择用户`)
        return
      }
      let { id = 0, nickName = '' } = this.currentRow
      this.subForm.user_id = id
      this.subForm.nickName = nickName
      this.showDialog = false
    },
    handleSelectionChange(val) {
      if(val.length > 1){
        this.$message.error(`请选择一个用户`)
        return
      }
      if (val && val[0]) {
        val = val[0];
        let { id, nickName } = val
        val.nickName = nickName || `用户ID ${id}`
        this.currentRow = val
      } else {
        this.currentRow = {}
      }
    },
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async toShowDialog() {
      let {
        have_user_id: have
      } = this
      if (have) return
      this.searchForm.nickName = ''
      await this.getTableDataList()
      this.showDialog = !this.showDialog
    },
    async getBaseInfo () {
      let { code, data } = await this.$api.agent.adminSelect()
      if (code !== 200) return
      this.base_agent = data
    },
    /**
     * @name: 详情
     * @param {*} id
     */
    async getDetail (id) {
      let { code, data } = await this.$api.store.storeInfo({ id })
      if (code !== 200) return
      data.doorstep_photo = [{ url: data.doorstep_photo }]
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    getCover (img, key) {
      this.subForm[key] = img
    },
    getLatLng (latLng) {
      this.subForm.lat = latLng.lat
      this.subForm.lng = latLng.lng
    },
    /**
     * @name: 新增/编辑
     * @param {*}
     */
    submitForm () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        subForm.doorstep_photo = subForm.doorstep_photo[0].url

        let isAllPhone = /((^400)-([0-9]{7})$)|(^1[3-9]\d{9}$)|((^0\d{2,3})-(\d{7,8})$)/
        if (subForm.mobile && !isAllPhone.test(subForm.mobile)) {
          this.$message.error(`请输入有效的联系电话`)
          return
        }

        let { lat = '', lng = '' } = subForm
        let isLng = /^[\-\+]?(0(\.\d{1,15})?|([1-9](\d)?)(\.\d{1,15})?|1[0-7]\d{1}(\.\d{1,15})?|180\.0{1,15})$/
        let isLat = /^[\-\+]?((0|([1-8]\d?))(\.\d{1,15})?|90(\.0{1,15})?)$/
        if ((lng && !isLng.test(lng)) || (lat && !isLat.test(lat))) {
          this.$message.error(lng && !isLng.test(lng) ? `请输入正确的经度` : `请输入正确的纬度`)
          return
        }

        // let methodModel = subForm.id ? 'storeUpdate' : 'storeAdd'
        this.$api.store.addQt(subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
            this.$refs.subForm.resetFields()
          }
        })
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.lb-store-manage-edit {
  width: 100%;
  .el-form {
    width: 100%;
    .el-select,
    .el-input-number,
    .el-input {
      width: 300px;
    }
    .el-textarea {
      width: 600px;
    }
  }
}
</style>
